package com.jn.exam.question.schedule;

import com.jn.exam.DateTimeUtil;
import com.jn.exam.question.service.PersonalQuestionService;
import com.jn.exam.question.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 江南大学1033190417
 * @date 2022/1/26 23:00
 */
@Component
@Slf4j
public class ScheduleTask {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private PersonalQuestionService personalQuestionService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Scheduled(cron = "0 0 1 * * ? ")
    //@Scheduled(cron = "0/5 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void task() {
        Boolean isExist = redisTemplate.hasKey("expire");
        if (Boolean.TRUE.equals(isExist)) {
            return;
        }
        redisTemplate.opsForValue().set("expire", "expire", 5, TimeUnit.MINUTES);
        Date date = DateTimeUtil.addDays(new Date(), -30);
        boolean isOK = questionService.deleteQuestionExpire(date);
        boolean isOK2 = personalQuestionService.deleteQuestionExpire(date);
        log.info("北京时间：{}清除题库中已删除30天的题目", DateTimeUtil.getSysTime());
    }
}
